package pers.cz.jefconfig.resource;

import pers.cz.jefconfig.io.IOUtils;
import pers.cz.jefconfig.log.LogUtils;
import pers.cz.jefconfig.tools.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * @program: JefConfig
 * @description: 压缩包资源
 * @author: Cheng Zhi
 * @create: 2022-07-15 15:12
 **/
public class ZipFileResource extends FileResource{

    private File zipFile;

    public ZipFileResource(URL url) {
        this.url = url;
        String filename = url.toString();
        try {
            String zipName= URLDecoder.decode(StringUtils.substringAfter(StringUtils.substringBefore(filename, "!"), "file:"),"UTF-8");
            zipFile = new File(zipName);
        } catch (UnsupportedEncodingException e1) {
            //never happens.
        }

        //filename=StringUtils.substringAfterLast(filename, "/")+"."+StringUtils.getCRC(filename);
        filename=StringUtils.substringAfterLast(filename, "/");
        File tempFile=new File(System.getProperty("java.io.tmpdir"),filename);
        if(tempFile.exists()){
            this.file=tempFile;
        }else{
            try {
                IOUtils.saveAsFile(tempFile, url.openStream());
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
            this.file=tempFile;
            LogUtils.info("The zipped resource is saved as: " + tempFile.getAbsolutePath());
        }
    }

    public File getZipFile() {
        return zipFile;
    }
}
